﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace UI
{
    public enum GridType
    {
        Horizontal,
        Vertical,
    }
    public class UnfixedGrid :UIWidgetContainer
    {
        private SortedList<GameObject, int> childrens = new SortedList<GameObject, int>();

        [SerializeField]
        private GridType type = GridType.Vertical;
        [SerializeField]
        private int cursor=0;
        [SerializeField]
        private int padding=0;
        
        
        public int Padding
        {
            get
            {
                return padding;
            }
        }


        public void ResetGrid()
        {
            cursor=0;
        }

        public void DestroyAll()
        {
            foreach( var it in childrens )
            {
                if(it.Key!=null)
                {
                    GameObject.Destroy( it.Key );
                }
            }

            childrens.Clear();
            cursor=0;
        }

        public void Add(GameObject item,UIWidget widget)
        {
            Add( item, type == GridType.Vertical?widget.height:widget.width );
        }

        public void Add( GameObject item, int value )
        {
            item.transform.SetParent( transform );
            item.transform.localScale =Vector3.one;

            Vector3 newPosition = type==GridType.Vertical?new Vector3( 0, -cursor, 0 ):new Vector3( cursor, 0, 0 );
            item.transform.localPosition = newPosition;

            cursor+=value;
            cursor+=padding;
        }

        public void Remove( GameObject item )
        {
            if( childrens.ContainsKey( item ) )
            {
                int height = childrens[item];
                childrens.Remove( item );

                cursor -= height;
                cursor -= padding;
            }
        }

        public void Reposition()
        {
            if( childrens.Count>0 )
            {
                cursor=0;
                foreach( var it in childrens )
                {
                    GameObject item = it.Key;
                    int height = it.Value;
                    item.transform.SetParent( transform );
                    item.transform.localScale =Vector3.one;

                    Vector3 newPosition = type==GridType.Vertical?new Vector3( 0, -cursor, 0 ):new Vector3( cursor, 0, 0 );
                    item.transform.localPosition = newPosition;

                    cursor+=height;
                    cursor+=padding;
                }
            }
        }

        void Update()
        {
            Reposition();
            enabled = false;
        }

        void OnValidate()
        {
            if (!Application.isPlaying && NGUITools.GetActive(this)) Reposition();
        }
    }
}